#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    int data;
    struct Node *next;
} Node_t, *Node_p;

Node_p Node_Init(int data)
{
    Node_p head = (Node_p)malloc(sizeof(Node_t));
    head->next = NULL;
    head->data = data;
    return head;
}

// 头插法
void Node_Insert(Node_p head, int data)
{
    Node_p node = (Node_p)malloc(sizeof(Node_t));
    node->data = data;
    node->next = head->next;
    head->next = node;
}

// 尾插法
void Node_Append(Node_p head, int data)
{
    Node_p node = (Node_p)malloc(sizeof(Node_t));
    node->data = data;
    node->next = NULL;
    Node_p p = head;
    while (p->next != NULL)
    {
        p = p->next;
    }
    p->next = node;
}

void Node_Print(Node_p head)
{
    Node_p p = head;
    while (p != NULL)
    {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

Node_p delete_node(Node_p head, int data)
{
    // 处理空链表情况
    if (head == NULL)
    {
        return NULL;
    }

    // 处理头节点是要删除的节点的情况
    if (head->data == data)
    {
        Node_p new_head = head->next;
        free(head);
        return new_head;
    }

    Node_p p = head;
    while (p->next != NULL)
    {
        if (p->next->data == data)
        {
            p->next = p->next->next;
            free(p->next);
            return p;
        }
        p = p->next;
    }
}

int main()
{
    Node_p head = Node_Init(0);
    // Node_Insert(head, 1);
    // Node_Insert(head, 2);
    // Node_Insert(head, 3);
    // Node_Insert(head, 4);

    Node_Append(head, 1);
    Node_Append(head, 2);
    Node_Append(head, 3);
    Node_Append(head, 4);

    Node_Print(head);
    head = delete_node(head, 0);
    Node_Print(head);
    head = delete_node(head, 1);
    head = delete_node(head, 2);
    Node_Print(head);
    return 0;
}